﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.Windows;
using System.Xaml;
using System.Windows.Markup;
using System.Reflection;


namespace Tanmia.Basis.WPF.Controls
{
    public class Labeler : ExtendedMarkupExtension
    {
        private IServiceProvider serviceProvider;
        private DependencyObject targetObject;
        private DependencyProperty targetProperty;

        public Labeler()
        {
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            string retValue = string.Empty;

            this.serviceProvider = serviceProvider;

            IRootObjectProvider rootObjectProvider = GetService<IRootObjectProvider>(serviceProvider);
            IProvideValueTarget provideValueTarget = GetService<IProvideValueTarget>(serviceProvider);

            if (provideValueTarget != null)
            {
                this.targetObject = provideValueTarget.TargetObject as DependencyObject;
                this.targetProperty = provideValueTarget.TargetProperty as DependencyProperty;
            }

            if (rootObjectProvider != null)
            {
                FrameworkElement rootObject = rootObjectProvider.RootObject as FrameworkElement;
                rootObject.DataContextChanged += new DependencyPropertyChangedEventHandler(rootObject_DataContextChanged);
            }

            if (Path != null && !string.IsNullOrEmpty(Path.Path))
                retValue = Path.Path.Substring(Path.Path.IndexOf('.') + 1);

            return retValue;
        }

        private void rootObject_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue != null)
            {
                PropertyInfo propInfo = GetPropertyByPath(e.NewValue, Path.Path);
                if (propInfo == null)
                    return;

                DisplayAttribute displayAttr = GetCustomAttribute<DisplayAttribute>(propInfo);

                if (displayAttr != null)
                    targetObject.SetValue(targetProperty, displayAttr.Name);
            }
        }

    }
}
